package v1

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/model"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/router/api"
	"zimuzu_cvn_web_api/router/api/app/middleware"
	"zimuzu_cvn_web_api/service"
)

type PassportAPI struct {
}

func (passport PassportAPI) Name() string {
	return "passport API"
}

func (passport PassportAPI) Bind() {
	passportAPI := config.C.Router.Group("/v1/admin/passport", middleware.TrackLog())
	{
		passportAPI.POST("login", login)
	}
	passport2API := config.C.Router.Group("/v1/admin/passport", middleware.TrackLog(), middleware.AuthMiddleware())
	{
		passport2API.GET("loginOut", loginOut)
	}
}

type loginParams struct {
	Account string `form:"account" json:"account" binding:"required"`
	Pwd     string `form:"pwd" json:"pwd" binding:"required"`
}

//登录提交
//Auth: Xu
func login(c *gin.Context) {
	var params loginParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	if !IsPhone(params.Account) {
		api.SendResponse(c, errors.New("请输入正确格式的手机号"), nil)
		return
	}

	loginIp := c.ClientIP()
	var user model.AdminUserDb
	user, checkloginErr := service.CheckAdminLogin(params.Account, params.Pwd)
	if checkloginErr != nil {
		if user.Id != 0 {
			service.AddLoginErrCount(loginIp, user.Id*100000)
		}
		api.SendResponse(c, checkloginErr, nil)
		return
	}

	token := service.CreateToken(service.LoginPlatformAdmin, user.Id, user.Pwd, user.NickName)
	responseData := map[string]interface{}{
		"uid":   user.Id,
		"token": token,
	}

	errno.OK.Info = "登录成功"
	api.SendResponse(c, errno.OK, responseData)
	return

}

type loginOutParams struct {
	Uid       int64  `form:"uid" json:"uid" binding:"required"`
	ShopToken string `form:"token" json:"shop_token"`
}

//退出登录
//Auth: Xu
func loginOut(c *gin.Context) {
	var params loginOutParams
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	err = service.AdminLoginOutClearToken(uid, service.LoginPlatformAdmin)
	if err != nil {
		api.SendResponse(c, errors.New("退出登录失败"), nil)
		return
	}

	errno.OK.Info = "退出登录成功"
	api.SendResponse(c, errno.OK, nil)
	return
}
